package hijava;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Storage15 {

    int count = 0;
    int max = 20;
    private Lock lock = new ReentrantLock();
    private Condition full = lock.newCondition();
    private Condition empty = lock.newCondition();

    public void add() {
        lock.lock();
        while (count >= max) {
            System.out.println(Thread.currentThread().getName() + ":仓库已满");
            try {
                full.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        count++;
        System.out.println(Thread.currentThread().getName() + ":【生产】了1个,当前的仓库数量是:" + count);
        empty.signalAll();
        lock.unlock();
    }

    public void subtract() {
        lock.lock();
        while (count <= 0) {
            System.out.println(Thread.currentThread().getName() + ":仓库-空");
            try {
                empty.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        count--;
        System.out.println(Thread.currentThread().getName() + ":【消费】了1个,当前的仓库数量是:" + count);
        full.signalAll();
        lock.unlock();
    }

}
